package com.coldworks.coldjoke.task;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Pair;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.coldworks.base.manager.BaseNetworkManager;
import com.coldworks.coldjoke.manager.JokeDbManager;
import com.coldworks.coldjoke.manager.UserManager;
import com.coldworks.coldjoke.ui.JokePageCell;
import com.coldworks.coldjoke.util.CONST;
import com.coldworks.coldjoke.util.NetworkUtil;

public class GetVoteTask extends AsyncTask<Void, Void, Pair<Integer, Integer>> {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	private Context context;
	private JokePageCell jokePageCell;
	private String jokesSort;
	private String jokeId;

	public GetVoteTask(Context context, JokePageCell jokePageCell,
			String pJokesSort) {
		this.context = context;
		this.jokePageCell = jokePageCell;
		this.jokesSort = pJokesSort;
		this.jokeId = jokePageCell.getJokeModel().getJokeId();
	}

	@Override
	protected Pair<Integer, Integer> doInBackground(Void... params) {
		if ((jokePageCell.getJokeModel().getLiked() < 0 || jokePageCell
				.getJokeModel().getDisliked() < 0)
				&& UserManager.getInstance().isLogin()) {

			String urlLiked = CONST.URL.PROFILE
					+ "?action=isJokeLiked&joke_id=" + jokeId;
			String urlDisliked = CONST.URL.PROFILE
					+ "?action=isJokeUnliked&joke_id=" + jokeId;
			int liked = this.excGet(urlLiked);
			int disliked = this.excGet(urlDisliked);
			return new Pair<Integer, Integer>(liked, disliked);
		} else {
			return null;
		}
	}

	@Override
	protected void onPostExecute(Pair<Integer, Integer> res) {
		super.onPostExecute(res);
		if (res != null) {
			if (this.jokeId.equals(jokePageCell.getJokeModel().getJokeId())) {

				if (res.first >= 0 && res.second >= 0) {
					jokePageCell.getJokeModel().setLiked(res.first);
					jokePageCell.getJokeModel().setDisliked(res.second);
					JokeDbManager.getInstance().updateOneJoke(context,
							jokesSort, jokePageCell.getJokeModel());
					log.info("get vote : (" + res.first + "," + res.second
							+ ")");
				} else {
					log.warn("get vote err");
					return;
				}
				if (res.first > 0 || res.second > 0) {
					jokePageCell.setLikeState(jokePageCell.likeStateDisable);
				} else {
					jokePageCell.setLikeState(jokePageCell.likeStateEnable);
				}
				return;
			} else {
				log.info("cell changed");
			}
		} else {
			log.info("login : " + UserManager.getInstance().isLogin()
					+ ". exist vote : ("
					+ jokePageCell.getJokeModel().getLiked() + ","
					+ jokePageCell.getJokeModel().getDisliked() + ")");
		}

		if (jokePageCell.getJokeModel().getLiked() > 0
				|| jokePageCell.getJokeModel().getDisliked() > 0) {
			jokePageCell.setLikeState(jokePageCell.likeStateDisable);
			log.info("like disable");
		} else {
			jokePageCell.setLikeState(jokePageCell.likeStateEnable);
			log.info("like enable");
		}
	}

	private int excGet(String url) {
		DefaultHttpClient httpclient;
		HttpGet get = new HttpGet(url);
		httpclient = BaseNetworkManager.getInstance().createHttpClient(context);
		try {
			String sessionId = UserManager.getInstance().getSessionId();
			get.setHeader("COOKIE", "webpy_session_id=" + sessionId);
			HttpResponse response = httpclient.execute(get);
			if (isCancelled()) {
				log.info("cancelled");
				return -1;
			}
			if (response.getStatusLine().getStatusCode() == 200) {
				Header contentEncoding = response
						.getFirstHeader("Content-Encoding");
				JSONObject jsonObject = null;
				if (contentEncoding != null
						&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
					jsonObject = NetworkUtil.getInstance().getJsonObjectByGzip(
							response.getEntity().getContent());
				} else {
					jsonObject = NetworkUtil.getInstance().getJSONObject(
							response.getEntity().getContent());
				}

				if (jsonObject == null) {
					log.info("json result == null");
					return -1;
				}

				if (jsonObject.getString("exists").equals("true")) {
					return 1;
				} else {
					return 0;
				}
			} else {
				log.warn(String.valueOf(response.getStatusLine()
						.getStatusCode()));
			}
		} catch (UnsupportedEncodingException e) {
			log.error("", e);
		} catch (IOException e) {
			log.error("", e);
		} catch (JSONException e) {
			log.error("", e);
		} finally {
		}
		return -1;
	}

}
